﻿using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Oracle.ManagedDataAccess.Client;
using Wantn.Core;
using Wantn.DAS.Msg.Common;
using Wantn.WinFormSys;

namespace Wantn.LMS
{
    /// <summary>
    /// 检验结果录入
    /// </summary>
    public partial class FrmResultInput : FrmBase
    {
        private static readonly string Url = ConfigurationManager.AppSettings["Url"];
        /// <summary>
        /// 默认构造方法
        /// </summary>
        public FrmResultInput()
        {
            InitializeComponent();
        }

        private void FrmResultInput_Load(object sender, EventArgs e)
        {
            DoQueryTarget();
        }

        private void DoQueryTarget()
        {
            var url = Url + "/common/querysql.do";
            var msg = new DasMsgQuerySql {Sql = "select t.f_scode,t.f_mark,t.f_unit,t.f_decimal,null as F_Result from T_B_TARGET t"};
            var reqContentPlain = JsonConvert.SerializeObject(msg);
            var result = DasClinet.SendPost(url, 30 * 1000, true, UserInfo.UserName, UserInfo.UserPwd, reqContentPlain);

            if (!result.IsSuccess || result.StatusCode != 1)
            {
                MessageBox.Show(@"查询数据失败" + "\n错误1：" + result.StatusDesc + "\n错误2：" + result.ErrInfo);
                return;
            }
            //反序列响应数据到具体的业务响应实体对象
            var jsonSet = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            msg = JsonConvert.DeserializeObject<DasMsgQuerySql>(result.ResponseContentPlain, jsonSet);

            if (msg.ResultDataset == null || msg.ResultDataset.Tables.Count <= 0 ||
                msg.ResultDataset.Tables[0].Rows.Count <= 0) return;

            foreach (DataRow row in msg.ResultDataset.Tables[0].Rows)
            {
                var newRow = dataTable1.NewRow();
                foreach (DataColumn column in dataTable1.Columns)
                {
                    newRow[column.ColumnName] = row[column.ColumnName];
                }
                dataTable1.Rows.Add(newRow);
            }
            dataTable1.AcceptChanges();
            //UltraGrid自适应宽度
            //utg_Main.DisplayLayout.Bands[0].PerformAutoResizeColumns(false, PerformAutoSizeType.AllRowsInBand);
        }

        private void ultraTool_ToolClick(object sender, Infragistics.Win.UltraWinToolbars.ToolClickEventArgs e)
        {
            switch (e.Tool.Key)
            {
                case "SaveResult":
                    DoSaveResult();
                    break;
            }
        }

        private void DoSaveResult()
        {
            var strBatchNo = ute_AsNo.Text.Trim();
            if (string.IsNullOrEmpty(strBatchNo))
            {
                MessageBox.Show("请输入化验编号!");
                ute_AsNo.Focus();
                return;
            }
            var strCodeResult = "";
            foreach (
                var ugr in utg_Main.Rows.Where(ugr => !string.IsNullOrEmpty(ugr.Cells["F_Result"].Value.ToString())))
            {
                if (strCodeResult.Length < 1)
                    strCodeResult += ugr.Cells["F_SCODE"].Value + ":" + ugr.Cells["F_Result"].Value;
                else
                    strCodeResult += "," + ugr.Cells["F_SCODE"].Value + ":" + ugr.Cells["F_Result"].Value;
            }
            var url = Url + "/Common/ExecProc.do";
            var msg = new DasMsgExecProc
            {
                ProcName = "PCK_ASSAYMANAGE.ASSAYRESULTINPUT",
                ProcParams = new[]
                {
                    new ProcParam
                    {
                        Name = "FCODE",
                        DbType = Convert.ToInt32(OracleDbType.NVarchar2),
                        Direction = ParameterDirection.Input,
                        Size = null,
                        Value = strBatchNo
                    },
                    new ProcParam
                    {
                        Name = "FCODERESULT",
                        DbType = Convert.ToInt32(OracleDbType.Varchar2),
                        Direction = ParameterDirection.Input,
                        Size = null,
                        Value = strCodeResult
                    },
                    new ProcParam
                    {
                        Name = "FUID",
                        DbType = Convert.ToInt32(OracleDbType.Decimal),
                        Direction = ParameterDirection.Input,
                        Size = null,
                        Value = UserInfo.UserId
                    },
                    new ProcParam
                    {
                        Name = "ERRCODE",
                        DbType = Convert.ToInt32(OracleDbType.Decimal),
                        Direction = ParameterDirection.Output,
                        Size = 10,
                        Value = 0
                    },
                    new ProcParam
                    {
                        Name = "ERRMSG",
                        DbType = Convert.ToInt32(OracleDbType.Varchar2),
                        Direction = ParameterDirection.Output,
                        Size = 1000,
                        Value = ""
                    }
                }
            };
            var reqContentPlain = JsonConvert.SerializeObject(msg);
            var dasClientResult = DasClinet.SendPost(url, 30*1000, true, UserInfo.UserName, UserInfo.UserPwd,
                reqContentPlain);
            if (!dasClientResult.IsSuccess || dasClientResult.StatusCode != 1)
            {
                MessageBox.Show("保存数据发生如下错误:\n错误1:" + dasClientResult.StatusDesc + "\n错误2:" + dasClientResult.ErrInfo);
                return;
            }
            var rspJson = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
            var rspMsg = JsonConvert.DeserializeObject<DasMsgExecProc>(dasClientResult.ResponseContentPlain, rspJson);

            if (rspMsg.ProcParams[3].Value.ToString() != "0")
            {
                MessageBox.Show("保存数据发生错误：" + rspMsg.ProcParams[4].Value);
                return;
            }
            foreach (var row in utg_Main.Rows)
            {
                row.Cells["F_RESULT"].Value = DBNull.Value;
            }
            MessageBox.Show("保存数据成功!");
        }

    }
} 